package com.webserver.core;

import com.webserver.http.HttpResponse;
import com.webserver.http.HttpRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于处理请求
 */
public class DispatcherServlet {
    public void service(HttpRequest request,HttpResponse response){
        String path  = request.getUri();
        File file = new File("./webapps"+path);
        if(file.exists()&&file.isFile()){
            response.setEntity(file);
            //资源存在
            Map<String,String>mimeMapping=new HashMap<>();
            mimeMapping.put("html","text/html");
            mimeMapping.put("css","text/css");
            mimeMapping.put("js","application/javascript");
            mimeMapping.put("png","image/png");
            mimeMapping.put("gif","image/gif");
            mimeMapping.put("jpg","image/jpeg");
            String fileName=file.getName();
            String  ext=fileName.substring(
                    fileName.lastIndexOf(".")+1
            );
            String type=mimeMapping.get(ext);

            response.addHeader("Content-Type",type);
            response.addHeader("Content-Length",file.length()+"");
        }else{
            //资源不存在
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File("./webapps/root/404.html");
            response.setEntity(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");
        }
        response.addHeader("Server","WebServer");
    }
}
